<?php
namespace Home\Controller;
use Think\Controller;

class PayController extends CommonController {
    private $alipay_config = null;//支付宝配置信息

    private $auth_status = 0;//默认：未认证
    private $user_email = null;//用户邮箱
    private $uid = null;
    private $user_token = null;
    private $auth_type = 1;
    private $user_tel = null;

    public function __construct(){
        parent::__construct();
        //是否普通用户，且是登录状态
        
        $this->getAuthStatus();
        $this->auth_status = session('37degree_auth_status');
        
        $this->user_email = session('user_email');
        $this->assign('user_email',$this->user_email);
        $this->uid = session('uid');
        $this->user_token = session('user_token');
        $this->auth_type = session('auth_type');
        $this->user_tel = session('user_tel');

        $this->assign('user_token',$this->user_token);
        
        // 用户信息
        if($this->role != -1){// 游客
            $this->user_email = session('user_email');
            $this->assign('user_email',$this->user_email);
        }
        $this->assign('role',$this->role);

        $this->alipay_config = array(
            //合作身份者ID，签约帐号，以2088开头由16位纯数字组成的字符串，查看地址：https://openhome.alipay.com/platform/keyManage.htm?keyType=partner
            'partner'=>C('PARTNER'),
            //收款支付宝帐号，以2088开头由16位纯数字组成的字符串，一般情况下收款帐号就是签约帐号
            'seller_id'=>C('SELLER_ID'),
            //商户的私钥,此处填写原始私钥去头去尾，RSA公私钥生成：https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.nBDxfy&treeId=58&articleId=103242&docType=1
            'private_key'=>trim(C('PRIVATE_KEY')),

            //支付宝的公钥，查看地址：https://b.alipay.com/order/pidAndKey.htm
            'alipay_public_key'=>trim(C('ALIPAY_PUBLIC_KEY')),
            // 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
            'notify_url'=>C('NOTIFY_URL'),
            // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
            'return_url'=>C('RETURN_URL'),
            //签名方式
            'sign_type'=> strtoupper( C('SIGN_TYPE') ),
            //字符编码格式 目前支持 gbk 或 utf-8
            'input_charset'=>trim(strtolower(C('INPUT_CHARSET'))),
            //ca证书路径地址，用于curl中ssl校验
            //请保证cacert.pem文件在当前文件夹目录中
            'cacert'=>getcwd().'\\cert\\alipaykey\\cacert.pem',
            //访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
            'transport'=>C('TRANSPORT'),
            // 支付类型 ，无需修改
            'payment_type'=>C('PAYMENT_TYPE'),
            // 产品类型，无需修改
            'service'=>C('SERVICE'),
            // 防钓鱼时间戳  若要使用请调用类文件submit中的query_timestamp函数
            'anti_phishing_key'=>C('ANTI_PHISHING_KEY'),
            // 客户端的IP地址 非局域网的外网IP地址，如：221.0.0.1
            'exter_invoke_ip'=>C('EXTER_INVOKE_IP')
        );
        $this->assign('head_title',"支付－云途数据市场");
    }

    //校验是否登录，认证，是否服务商帐号
    private function checkBuyUser($isAjax = false){
        $return = true;
        $msg = 'OK';
        $status = 200;

        if(empty($this->uid)){
            $return = false;
            $msg = "请登录";
            $status = 4001;
        }else if($this->auth_status!=2){
            $return = false;
            $msg = "请认证";
            $status = 4002;
        }
        //去掉购买限制，服务商用户也可以购买
        // if($this->role==2){
        //     $return = false;
        //     $msg = "请登录普通用户帐号购买";
        //     $status = 4003;
        // }

        if($return != true){
            if($isAjax){
                $this->ajaxReturn( array('status'=>$status,'msg'=>$msg,'data'=>null));
            }
        }else{
            return array('status'=>$status,'msg'=>$msg,'data'=>null);
        }


    }

    public function index(){
        // $alipay_config = load_config("alipay.php");
        // echo "<pre>";print_r($this->alipay_config);die;
        //加载函数库
        load("@.alipay_core");

        $test_array = array(3453,43,234,2,4,100);
        $test_arrays = argSort($test_array);
        echo "<pre>";print_r($test_arrays);die;
        echo "pay";die;
    }

    //支付方式页
    public function info(){
        //是否登录认证
        $check_result = $this->checkBuyUser();

        if($check_result['status']!=200){
            switch($check_result['status']){
                case 4002:
                    //redirect("/",'5','4002');
                    $this->error('请认证','/');
                    break;
                case 4003:
                    // redirect("/",'5','4003');
                    $this->error('请登录云途用户帐号购买','/');
                    break;
                default:
                    // redirect("/member/login.html",'5','需要登录');
                    $this->error('请登录','/member/login.html');
                    break;
            }
        }

        //条件判断
        $service_id = I('post.service_id',0,'intval');
        $api_id = I('post.api_id',0,'intval');

        $package_name = I('post.package_name','');//前后各4位随机数，中间为真正名称

        //对名称进行解密处理---todo
        $real_package_name = $package_name;

        if($service_id==0 || !is_numeric($service_id) || $api_id==0 || !is_numeric($api_id) || empty($package_name)){
            // redirect("/",'5','ERROR DATA');
            $this->error('ERROR DATA','/');
        }
        //查询详情
        $serviceModel = D('ServiceApisImage');
        $info = $serviceModel->getInfo($api_id);
        
        //是否存在该
        if(!empty($info)){
            if($info['service_id']==$service_id){
                //是否存在该套餐，改api状态是否在线
                if($info['api_enable']!=1){
                    // redirect("/",'5','down API');
                    $this->error('down API','/');
                }
                //是否免费
                if($info['api_is_charge']==0){
                    // redirect("/",'5','free API');
                    $this->error('free API','/');
                }
                $all_package = json_decode($info['api_charge_rules'],true);
                $package_exists = false;
                $price = 100000;
                $cycle = "";
                foreach ($all_package as $p_k=>$p_v){
                    if($p_v['package_name']==$package_name){
                       $price = $p_v['package_price'];
                       $cycle = $p_v['package_cycle'];
                       $package_exists = true;
                    }
                }
                if($package_exists===false){
                    $this->error('ERROR DATA','/');
                }
                $info['price'] = $price;
                $info['cycle'] = $cycle;
                $info['package_name'] = $package_name;
                
                $this->assign('info',$info);

                $this->display("info");

            }else{
                $this->error('ERROR DATA','/');
            }
        }else{
            // redirect("/",'5','NO THE API');
            $this->error('NO THE API','/');
        }

    }

    //重新支付--方式页（继续支付订单）
    public function keeppay(){
        //是否登录认证
        $check_result = $this->checkBuyUser();
        if($check_result['status']!=200){
            switch($check_result['status']){
                case 4002:
                    //redirect("/",'5','4002');
                    $this->error('请认证','/');
                    break;
                case 4003:
                    // redirect("/",'5','4003');
                    $this->error('请登录云途用户帐号购买','/');
                    break;
                default:
                    // redirect("/member/login.html",'5','需要登录');
                    $this->error('请登录','/');
                    break;
            }
        }

        $order_id = I('post.order_id',null);
        if(!empty($order_id)){
            //获取订单信息
            $orderModel = D('Order');
            $info = $orderModel->getInfo($order_id);

            //是否该用户
            if($this->uid!=$info['user_id']){
                $this->error('您无权限支付该订单','/');
            }
            //是否已支付
            if(in_array($info['pay_status'],array(1,2))){
                $this->error('改订单已支付成功','/');   
            }
            //获取价格，订单名称等信息（不是免费的）
            $all_package = json_decode($info['condition_json'],true);
            $info['price'] = $all_package['package_price'];
            $info['cycle'] = $all_package['package_cycle'];
            $info['package_name'] = $info['package_name'];

            $this->assign('info',$info);
            $this->display('keeppay');

        }else{
            $this->error('订单不存在','/');
        }
    }

    //点击购买时（目前只处理免费购买）
    public function ajaxApplyBuy(){
        //是否登录认证
        $this->checkBuyUser($isAjax=true);

        $params = I('post.');
        //获取服务id
        if(!isset($params['service_id']) || empty($params['service_id']) ){
            $this->ajaxReturn( array('status'=>400,'msg'=>'缺少必要参数','data'=>null));
        }
        //获取api——id
        if(!isset($params['api_id']) || empty($params['api_id']) ){
            $this->ajaxReturn( array('status'=>400,'msg'=>'缺少必要参数','data'=>null));
        }
        //获取套餐名称
        $package_name = $params['package_name'];

        $serviceModel = D('ServiceApisImage');
        $info = $serviceModel->getInfo($params['api_id']);

        //是否可用
        if($info['api_enable'] != 1 ){
            $this->ajaxReturn( array('status'=>400,'msg'=>'该API已下线','data'=>null));
        }

        //是否曾下单（需要考虑某api从收费改为免费情形）
        $orderModel = D('Order');
        
        if($info['api_is_charge']==0){
            $free_order_count = $orderModel->freeApiSearch($info['api_id'],$info['service_id'],$this->uid);
            if($free_order_count){
                $this->ajaxReturn( array('status'=>4006,'msg'=>'您已购买该API','data'=>null));
            }
            //下单入库---以后能否交给异步，队列服务器处理呢？？？？todo
            $gateway_params['service'] = $info['service_name_en'];
            $gateway_params['api'] = $info['api_name_en'];
            $gateway_params['user'] = $this->user_email;
            $gateway_params['cnt_limit'] = 0;
            //请求网关
            $gateway_result = $this->gatewayAuthadd($gateway_params);
            
            if($gateway_result['status']==200 || $gateway_result['status']=='-10014007'){
                //免费--下单
                // $order_result = $this->generateOrder($info);
                $order_data = $this->getOrderData($info);
                if($order_data===false){
                    $this->ajaxReturn( array('status'=>400,'msg'=>"数据异常",'data'=>null));
                }
                $orderModel = D('Order');
                $order_result = $orderModel->writeOrder($order_data);
                //该服务购买数量增加+1call_num---modify 20161024 -start
                $serviceModel = M('Services');
                $serviceModel->where("service_id=".$order_data['service_id'])->setInc('call_num');
                //该服务购买数量增加+1call_num---modify 20161024 -end

                if(!$order_result){
                    $destination = C('LOG_PATH').'order_faild/'.date('y_m_d').'.log';
                    $message = "免费购买-".$info['service_name']."-".$info['api_name']."-".date('Y-m-d H:i:s');
                    $level = \Think\Log::ERR;
                }else{
                    $destination = C('LOG_PATH').'order_success/'.date('y_m_d').'.log';
                    $message = "免费购买-".$info['service_name']."-".$info['api_name']."-".date('Y-m-d H:i:s');
                    $level = \Think\Log::INFO;
                }
                \Think\Log::write($message,$level,$type='',$destination);

                if($order_result){
                    $this->ajaxReturn( array('status'=>200,'msg'=>'OK','data'=>null));
                }else{
                    $this->ajaxReturn( array('status'=>400,'msg'=>"下单库出现问题",'data'=>null));
                }

            }else{
                $error_msg = json_decode( $gateway_result['result'] ,true);
                $this->ajaxReturn( array('status'=>$error_msg['status'],'msg'=>$error_msg['return_msg'],'data'=>null));
            }
            

        }else if ($info['api_is_charge']==1){
            //收费
            if(empty($info['api_charge_rules'])){
                $this->ajaxReturn( array('status'=>500,'msg'=>'套餐数据存在问题','data'=>null));
            }
            if(empty($package_name)){
                $this->ajaxReturn( array('status'=>400,'msg'=>'请选择购买套餐','data'=>null));   
            }
            $all_charge_rules = json_decode($info['api_charge_rules'],true);
            $package_exists = false;
            $package_price = 0;
            foreach($all_charge_rules as $rules_key=>$rules_val){
                if($rules_val['package_name']==$package_name) {
                    $package_exists = true;
                    $package_price = $ruels_val['package_price'];
                }
            }

            if($package_exists!==true){
                $this->ajaxReturn( array('status'=>400,'msg'=>'请选择购买套餐','data'=>null));
            }

            //跳转到支付方式页？？？？？todo
            $this->ajaxReturn(array('status'=>200,'msg'=>'可以购买','data'=>'OK'));
        }

    }

    //获取下单数据信息
    private function getOrderData($info,$package_name = null,$pay_platform = 1){
        if(empty($info) ) return false;

        $insert_data['email'] = $insert_data['user_name'] = $this->user_email;
        $insert_data['user_id'] = $this->uid;
        $insert_data['service_id'] = $info['service_id'];
        $insert_data['service_name'] = $info['service_name'];
        $insert_data['service_name_en'] = $info['service_name_en'];
        $insert_data['order_id'] = gorderid();//加上日期 todo

        if(!empty($package_name)){
            //校验套餐名称是否存在
            $all_package = json_decode($info['api_charge_rules'],true);
            $package_exists = false;
            foreach ($all_package as $p_k=>$p_v){
                if($p_v['package_name']==$package_name){
                    $package_exists = true;
                    $insert_data['package_name'] = $package_name;
                    $insert_data['amount'] = $p_v['package_price'];
                    $insert_data['limit_num'] = $p_v['limit_num'];
                    $insert_data['condition_json'] = json_encode($p_v);
                    $insert_data['package_cycle'] = $p_v['package_cycle'];//add by tim 20160907
                    // expire_time----付款成功时
                    // begin_time----付款成功时
                }
            }
            if($package_exists===false) return false;
            $insert_data['pay_platform'] = $pay_platform;
            $insert_data['enable'] = 1;//订单暂时没有生效
        }else{
            $insert_data['pay_time'] = time();
            $insert_data['pay_status'] = 2;//免费支付
            $insert_data['enable'] = 1;
        }
        $insert_data['api_id'] = $info['api_id'];
        $insert_data['api_name'] = $info['api_name'];
        $insert_data['api_name_en'] = $info['api_name_en'];
        $insert_data['order_time'] = time();
        $insert_data['works_uid'] = $info['uid'];//服务所属用户uid
        $insert_data['user_mobile'] = $this->user_tel;//用户联系电话

        return $insert_data;
    }

    //继续支付下一步
    public function repay(){
        //是否登录认证
        $this->checkBuyUser($isAjax=true);

        $pay_platform = I('post.platform',1,'intval');
        if( !in_array( $pay_platform,array(1,2) ) ){
            $this->error('暂不支持改支付平台','/');
        }
        $order_id = I('post.order_id',null);
        if(empty($order_id)){
            $this->error('缺失必要参数','/');   
        }

        //查看订单
        $orderModel = D('Order');
        $order_info = $orderModel->getInfo($order_id);

        //直接支付
        if(!empty($order_info)){
            //是否该用户，是否已支付
            if( in_array($order_info['pay_status'],array(1,2) ) ){
                $this->error('该订单已支付成功','/');
            }
            if($pay_platform==1){
                $pay_platform_name = "支付宝";
            }else if($pay_platform==2){
                $pay_platform_name = "微信平台";
            }
            $destination = C('LOG_PATH').'repay_order/'.date('y_m_d').'.log';
            $message = "重新支付-".$order_info['service_name']."-".$order_info['api_name']."-"."-".$order_info['package_name']."-".$pay_platform_name."-".date('Y-m-d H:i:s');
            $level = \Think\Log::INFO;
            \Think\Log::write($message,$level,$type='',$destination);

            if($pay_platform==1){
                $this->alipay($order_info);//支付宝
            }else if($pay_platform==2){
                $this->wxpay($order_info);//微信支付
            }
        }else{
            $this->error("该订单不存在",'/');
            //$this->ajaxReturn( array('status'=>400,'msg'=>"下单库出现问题",'data'=>null));
        }

    }

    //付费API下单（支付方式下一步动作）
    public function pay(){
        //是否登录认证
        $this->checkBuyUser($isAjax=true);

        $params = I('post.');
        //获取服务id
        if(!isset($params['service_id']) || empty($params['service_id']) ){
            $this->error("缺少必要参数",'/');
            // $this->ajaxReturn( array('status'=>400,'msg'=>'缺少必要参数','data'=>null));
        }
        //获取api——id
        if(!isset($params['api_id']) || empty($params['api_id']) ){
            $this->error("缺少必要参数",'/');
            // $this->redirect("/","缺少必要参数");
            // $this->ajaxReturn( array('status'=>400,'msg'=>'缺少必要参数','data'=>null));
        }
        //获取套餐名称
        $package_name = $params['package_name'];

        $serviceModel = D('ServiceApisImage');
        $info = $serviceModel->getInfo( (int)$params['api_id']);

        //是否可用
        if($info['api_enable'] != 1 ){
            $this->error("该API已下线",'/');
            // $this->ajaxReturn( array('status'=>400,'msg'=>'该API已下线','data'=>null));
        }

        $pay_platform = (int)$params['platform'];
        //改api是否免费
        if($info['api_is_charge']==1){
            //下单（服务名称，api名称，套餐等等信息）----（付款回调方法中：请求网关，改写订单状态，流水记录表，服务商帐号收款）---日志-------
            // $order_result = $this->generateOrder($info,$package_name,$pay_platform);
            $order_data = $this->getOrderData($info,$package_name,$pay_platform);
            if($order_data===false){
                $this->error('数据异常','/');
            }
            
            $orderModel = D('Order');
            $order_result = $orderModel->writeOrder($order_data);

            if($pay_platform==1){
                $pay_platform_name = "支付宝";
            }else if($pay_platform==2){
                $pay_platform_name = "微信平台";
            }
            if(!$order_result){
                $destination = C('LOG_PATH').'order_faild/'.date('y_m_d').'.log';
                $message = "下单失败-".$info['service_name']."-".$info['api_name']."-"."-".$package_name."-".$pay_platform_name."-".date('Y-m-d H:i:s');
                $level = \Think\Log::ERR;
            }else{
                $destination = C('LOG_PATH').'order_success/'.date('y_m_d').'.log';
                $message = "下单成功-".$info['service_name']."-".$info['api_name']."-"."-".$package_name."-".$pay_platform_name."-".date('Y-m-d H:i:s');
                $level = \Think\Log::INFO;
            }
            \Think\Log::write($message,$level,$type='',$destination);

            if($order_result){
                if($pay_platform==1){
                    $this->alipay($order_data);//支付宝
                }else if($pay_platform==2){
                    $this->wxpay($order_data);//微信支付
                }
            }else{
                $this->error("系统异常",'/');
                //$this->ajaxReturn( array('status'=>400,'msg'=>"下单库出现问题",'data'=>null));
            }

        }else if ($info['api_is_charge']==0){
            $this->error("该API免费",'/');
            // $this->ajaxReturn(array('status'=>4005,'msg'=>'该API免费','data'=>'OK'));
        }

    }

    //支付方式页，支付宝处理
    private function alipay($info){
        header("Content-type:text/html;charset=utf-8");
        Vendor('Pay.alipay.alipay_submit','','.class.php');

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $info['order_id'];

        //订单名称，必填
        $subject = $info['api_name'];

        //付款金额，必填
        $total_fee = $info['amount'];
        // $total_fee = 0.01;

        //商品描述，可空---format-服务名称-ceshi0032-邮箱-用户id-服务编号-api编号-套餐名称
        // $body = $info['service_name']."-".$info['api_name']."-".$info['email']."-".$info['user_id'];
        $body = $info['api_name']."-".$info['email']."-".$info['user_id'];
        $body .="-".$info['service_id']."-".$info['api_id']."-".$info['package_name'];

        // echo $subject;die;
        /************************************************************/
        //构造要请求的参数数组，无需改动
        $parameter = array(
                "service"       => C(SERVICE),
                "partner"       => C(PARTNER),
                "seller_id"  => C(SELLER_ID),
                "payment_type"  => C(PAYMENT_TYPE),
                "notify_url"    => C(NOTIFY_URL),
                "return_url"    => C(RETURN_URL),
                "anti_phishing_key"=>C(ANTI_PHISHING_KEY),
                "exter_invoke_ip"=>C(EXTER_INVOKE_IP),
                "out_trade_no"  => $out_trade_no,
                // "subject"   => mb_convert_encoding($subject, 'utf-8', 'gb2312'),
                "subject"  =>$subject,
                "total_fee" => $total_fee,
                "body"  => "",
                "extra_common_param"=>$body,
                "_input_charset"    => C(INPUT_CHARSET),
                
        );
        // echo "<pre>";print_r($this->alipay_config);die;
        $alipaySubmit = new \AlipaySubmit($this->alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "SUBMIT");

        echo $html_text;
        return true;
    }

    //支付方式页，微信支付处理
    private function wxpay($info){
        //模式二
        /**
         * 流程：
         * 1、调用统一下单，取得code_url，生成二维码
         * 2、用户扫描二维码，进行支付
         * 3、支付完成之后，微信服务器会通知支付成功
         * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
         */
        ini_set('date.timezone','Asia/Shanghai');
        error_reporting(E_ERROR);
        Vendor('Pay.wxpay.WxPay#Api','','.php');
        Vendor('Pay.wxpay.WxPay#NativePay','','.php');
        Vendor('Pay.wxpay.log','','.php');
        $notify = new \NativePay();

        $input = new \WxPayUnifiedOrder();

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $info['order_id'];

        //订单名称，必填
        $subject = $info['api_name'];

        //付款金额，必填
        $total_fee = $info['amount'];
        // $total_fee = 0.01;

        //商品描述，可空---format-服务名称-ceshi0032-邮箱-用户id-服务编号-api编号-套餐名称
        //$body = $info['service_name']."-".$info['api_name']."-".$info['email']."-".$info['user_id'];
        $body = $info['api_name']."-".$info['email']."-".$info['user_id'];
        $body .="-".$info['service_id']."-".$info['api_id']."-".$info['package_name'];

        $input->SetBody($subject);
        $input->SetAttach($body);
        // $input->SetOut_trade_no(C('WEIXINPAY_CONFIG.MCHID').date("YmdHis"));
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($info['service_name']);
        $input->SetNotify_url(C('WEIXINPAY_CONFIG.NOTIFY_URL'));
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($info['api_id']);
        $result = $notify->GetPayUrl($input,$timeout=600);

        if($result['return_code']!='FAIL'){
            $this->assign('qrcode',$result["code_url"]);

            $all_package = json_decode($info['condition_json'],true);
            $this->assign('subject',$subject);
            $this->assign('total_fee',$total_fee);
            $this->assign('cycle',$all_package['package_cycle']);
            $this->assign('out_trade_no',$out_trade_no);

            $this->display('wxinfo');
        }else{
            $this->error($result['return_msg'],'/index/detail.html?sid='.$info['service_id']);
        }

    }




// 不需要用到--全部使用公用的 start  xxxxxxxxxxxxxxxxxxxxxxxx
    //异步通知
    public function alipay_notify(){
        header("Content-type:text/html;charset=utf-8");
        $data = I('post.');

        //支付宝验签
        Vendor('Pay.alipay.alipay_notify','','.class.php');
        $alipayNotify = new \AlipayNotify($this->alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        //判断支付状态，是否成功
        if($verify_result){
            if($data['trade_status']=='TRADE_SUCCESS'){
                //支付宝回调记录
                $pay_fail_destination = C('LOG_PATH').'alipay_notify/'.date('y_m_d').'.log';
                $pay_fail_message = "支付宝回调-验签成功记录:".$data['out_trade_no']."--支付宝交易编号：".$data['trade_no']."-金额:".$data['total_fee']."元人民币-"."-购买用户邮箱:".$data['buyer_email']."-商品信息:".$data['body']."---回调信息:".json_encode($data);
                \Think\Log::write($pay_fail_message,'INFO',$type='',$pay_fail_destination);

                // $orderModel = D('Order');
                // $order_info = $orderModel->getInfo($data['out_trade_no']);
                $orderModel = M('Orders');
                $order_info = $orderModel->where("order_id='".$data['out_trade_no']."'")->find();
                // echo "<pre>";print_r($order_info);
                if(!empty($order_info) && ( $order_info['pay_status']==0 || $order_info['pay_status']==-1) ){
                    //更新订单状态
                    try{
                        $this->alipay_success_update_table($data);
                    }catch(exception $e){
                       \Think\Log::write("exception",'INFO',$type='',C('LOG_PATH').'test/'.date('y_m_d').'.log'); 
                    }
                }
                echo "success";DIE;
            }else{
                //订单支付失败

                //日志
                $pay_fail_destination = C('LOG_PATH').'alipay_notify/'.date('y_m_d').'.log';
                $pay_fail_message = "支付宝回调-验签成功-支付失败记录:".$data['out_trade_no']."--支付宝交易编号：".$data['trade_no']."-金额:".$data['total_fee']."元人民币-"."-购买用户邮箱:".$data['buyer_email']."-商品信息:".$data['body']."---回调信息:".json_encode($data);
                \Think\Log::write($pay_fail_message,'INFO',$type='',$pay_fail_destination);

                ECHO "fail";DIE;
                //$this->error('支付失败');
            }
            
        }else{
            //订单支付失败

            //日志
            $pay_fail_destination = C('LOG_PATH').'alipay_notify/'.date('y_m_d').'.log';
            $pay_fail_message = "支付宝回调-验签失败记录:".$data['out_trade_no']."--支付宝交易编号：".$data['trade_no']."-金额:".$data['total_fee']."元人民币-"."-购买用户邮箱:".$data['buyer_email']."-商品信息:".$data['body']."---回调信息:".json_encode($data);
            \Think\Log::write($pay_fail_message,'INFO',$type='',$pay_fail_destination);

            ECHO "fail";DIE;
            //$this->error('支付失败');
        }

    }

    //alipay返回直接结果
    public function alipay_return(){
        header("Content-type:text/html;charset=utf-8");
        $data = I('get.');
        
        //支付宝校验
        Vendor('Pay.alipay.alipay_notify','','.class.php');

        $alipayNotify = new \AlipayNotify($this->alipay_config);
        $verify_result = $alipayNotify->verifyReturn();

        // $this->alipay_success_update_table($data);die;
        //验签---判断支付状态，是否成功
        if($verify_result){
            if($data['trade_status']=='TRADE_SUCCESS'){
                $orderModel = M('Orders');
                $order_info = $orderModel->where("order_id='".$data['out_trade_no']."'")->find();
                if(!empty($order_info) && ( $order_info['pay_status']==0 || $order_info['pay_status']==-1) ){
                   //更新订单状态
                   $this->alipay_success_update_table($data); 
                }
                
                $this->assign('amount',$data['total_fee']);
                $this->display('success');
            }else{
                //订单支付失败

                //日志
                $pay_fail_destination = C('LOG_PATH').'pay_fail/'.date('y_m_d').'.log';
                $pay_fail_message = "付款失败-订单编号:".$order_id."-金额:".$data['total_fee']."元人民币-"."-用户邮箱:".$user_email."-用户uid:".$user_id."-服务编号:".$service_id."-API编号:".$api_id."-套餐名称:".$package_name."-返回信息：".json_encode($data);
                \Think\Log::write($pay_fail_message,'INFO',$type='',$pay_fail_destination);

                $this->display('fail');
                // $this->error('支付失败','/');
            }
            

        }else{
            //订单支付失败

            //日志
            $pay_fail_destination = C('LOG_PATH').'pay_fail/'.date('y_m_d').'.log';
            $pay_fail_message = "验签失败-订单编号:".$order_id."-金额:".$data['total_fee']."元人民币-"."-用户邮箱:".$user_email."-用户uid:".$user_id."-服务编号:".$service_id."-API编号:".$api_id."-套餐名称:".$package_name."-返回信息：".json_encode($data);
            \Think\Log::write($pay_fail_message,'INFO',$type='',$pay_fail_destination);

            $this->display('fail');
            // $this->error('支付失败','/');
        }

    }    

    //wxpay回调url
    public function wxpay_notify(){
        ini_set('date.timezone','Asia/Shanghai');
        Vendor('Pay.wxpay.WxPay#Api','','.php');
        Vendor('Pay.wxpay.WxPay#Notify','','.php');

        $notify = new \WxPayNotify();
        $needSign = false;
        $result = $notify->Handle($needSign);

        $wxpay_destination = C('LOG_PATH').'wxpay_notify/'.date('y_m_d').'.log';
        $xml = file_get_contents("php://input"); 

        if($result){//验签成功
            // $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
            $xml_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            $xml_data['extra_common_param'] = $xml_data['attach'];
            $xml_data['notify_time'] = $xml_data['time_end'];
            $xml_data['total_fee'] = round($xml_data['total_fee']/100,2);//微信支付最小单位是“分”

            //入库--todo
            $result = $this->alipay_success_update_table($xml_data);
            if($result) {
                $notify->ReplyNotify($needSign);//稍后去掉注释
                
                $pay_ok_message = "wx_pay:ok-";
                $pay_ok_message .= json_encode($xml_data);
                
                \Think\Log::write($pay_ok_message,'INFO',$type='',$wxpay_destination);
            }else{
                $pay_ok_message = "wx_pay:insert into table fail-";
                $pay_ok_message .= json_encode($xml_data);

                \Think\Log::write($pay_ok_message,'INFO',$type='',$wxpay_destination);
            }

        }else{
            $pay_ok_message = "wx_pay:wx_fail-";
            $xml_data_new = $notify->FromXml($xml);
            $pay_ok_message .= json_encode($xml_data_new);

            \Think\Log::write($pay_ok_message,'INFO',$type='',$wxpay_destination);
        }
    }
// 不需要用到--全部使用公用的 end  xxxxxxxxxxxxxxxxxxxxxxxx







    //微信支付成功后页面-自己程序跳转
    public function wxpay_return(){
        header("Content-type:text/html;charset=utf-8");
        $order_id = I('get.orderid');
        $orderModel = M('Orders');
        $order_info = $orderModel->where("order_id='".$order_id."'")->find();
        if(empty($order_info) ){
           //更新订单状态
           error('改订单不存在');
        }
        
        $this->assign('amount',$order_info['amount']);
        $this->display('success');

    }

    //微信查询订单结果
    public function wxquery(){
        $out_trade_no = I('post.id',0,'trim');

        if(empty($this->uid)){
            $this->ajaxReturn( array('status'=>4003,'msg'=>'请登录','data'=>null));
        }
        if(empty($out_trade_no)){
            $this->ajaxReturn( array('status'=>4004,'msg'=>'缺少必要参数','data'=>null));
        }

        $orderModel = D('Order');
        $result = $orderModel->wxOrderResult($out_trade_no);
        if($result){
            $this->ajaxReturn( array('status'=>200,'msg'=>'OK','data'=>null));
        }else{
            $this->ajaxReturn( array('status'=>4005,'msg'=>'暂未支付','data'=>null));  
        }
    }

    private function alipay_success_update_table($data){
        //获取订单信息：订单编号，根据订单编号查询订单信息
        $order_id = $data['out_trade_no'];
        // $all_body = explode("-", $data['body']);
        $all_body = explode("-",$data['extra_common_param']);

        //$service_name = $all_body[0];
        $api_name = $all_body[0];
        $user_email = $all_body[1];
        $user_id = $all_body[2];
        $service_id = $all_body[3];
        $api_id = $all_body[4];
        $package_name = $all_body[5]; 
        
        $orderModel = M('Orders');
        $order_info = $orderModel->where("order_id='".$order_id."'")->find();

        //下单失败，付款成功时---记录日志，短信通知
        if(empty($order_info)){
            //日志
            $faild_order_destination = C('LOG_PATH').'faild_order_db/'.date('y_m_d').'.log';
            $order_faild_message = "订单库查找该订单失败,付款成功-订单编号:".$order_id."-金额:".$data['total_fee']."元人民币-"."-用户邮箱:".$user_email."-用户uid:".$user_id."-服务编号:".$service_id."-API编号:".$api_id."-套餐名称:".$package_name."--导致更新订单及账户金额，请求网关没有处理";

            \Think\Log::write($order_faild_message,'ERR',$type='',$faild_order_destination);

            return false;
            // $this->error('系统异常');
        }

        //请求网关
        $gateway_params['service'] = $order_info['service_name_en'];
        $gateway_params['api'] = $order_info['api_name_en'];
        $gateway_params['user'] = $user_email;
        $gateway_params['cnt_limit'] = 1;//访问频率限制
        $gateway_params['rate_limit'] = 1;//访问次数限制

        // expire_time     int     否   访问过期时间 unixtime -1为永远不过期 默认为-1
        //获取最后一次付款成功过期时间-开始时间 + 天数
        $orderModel = D('Order');
        $surplus_time = $orderModel->getSuccessOrderTime($user_id,$api_id);

        $condition_json = json_decode($order_info['condition_json'],true);
        $day = 31;//周期
        isset($condition_json['package_date'])?($day=$condition_json['package_date']):($day = 31);
        $expire_time = $day * 24 * 3600; 

        $gateway_params['expire_time'] = time() + $expire_time + $surplus_time;
        //频次时间限制-请求网关
        //查询用户购买记录（已经成功付款）
        $order_api_verify = $orderModel->verifyApiWithUid($user_id,$order_info['service_id'],$order_info['api_id']);
        if($order_api_verify!==false){
            if($order_api_verify==0){//没有购买记录
                $gateway_result = $this->gatewayAuthadd($gateway_params);
                $gateway_authadd_destination = C('LOG_PATH').'gateway_auth_add/'.date('y_m_d').'.log';
                \Think\Log::write(json_encode($gateway_result),'INFO',$type='',$gateway_authadd_destination);

                //请求条数限制-请求网关
                $gateway_order['service'] = $order_info['service_name_en'];
                $gateway_order['api'] = $order_info['api_name_en'];
                $gateway_order['user'] = $user_email;
                $gateway_order['cnt'] = $order_info['limit_num'];
                $gateway_order_result = $this->gatewayOrdervary($gateway_order);
                $gateway_order_destination = C('LOG_PATH').'gateway_order/'.date('y_m_d').'.log';
                \Think\Log::write(json_encode($gateway_order_result),'INFO',$type='',$gateway_order_destination);
            }else{
                $gateway_result = $this->gatewayAuthupdate($gateway_params);
                $gateway_authadd_destination = C('LOG_PATH').'gateway_auth_add/'.date('y_m_d').'.log';
                \Think\Log::write(json_encode($gateway_result),'INFO',$type='',$gateway_authadd_destination);

                //请求条数限制-请求网关
                $gateway_order['service'] = $order_info['service_name_en'];
                $gateway_order['api'] = $order_info['api_name_en'];
                $gateway_order['user'] = $user_email;
                $gateway_order['cnt'] = $order_info['limit_num'];

                //购买产品是否过期---todo
                if($surplus_time===0){//有购买，但购买产品过期
                    $gateway_order_result = $this->gatewayOrderSet($gateway_order);//todo
                }else{
                    $gateway_order_result = $this->gatewayOrdervary($gateway_order);  
                }

                // echo "<pre>gatewau-------------";print_r($gateway_order_result);die;
                $gateway_order_destination = C('LOG_PATH').'gateway_order/'.date('y_m_d').'.log';
                \Think\Log::write(json_encode($gateway_order_result),'INFO',$type='',$gateway_order_destination);
            }
        }else{
            return false;
        }
        
        //开启事务
        $orderModel->startTrans();
        //改写订单状态，流水记录表，服务商帐号收款
        $pay_time = strtotime($data['notify_time']);
        $order_data = array('pay_status'=>1,"pay_time"=>$pay_time,"begin_time"=>$pay_time,'expire_time'=>$gateway_params['expire_time'],'pay_status'=>1,'enable'=>1,'pay_platform_name'=>$data['buyer_email'],'expire_time'=>$gateway_params['expire_time']);
        $update_order_status = $orderModel->where("order_id='".$order_id."'")->save($order_data);

        $payhistoryModel = M('PaymentsHistory');
        $pay_history_data = array('from_uid'=>$order_info['user_id'],'from_username'=>$order_info['user_name'],'to_uid'=>$order_info['works_uid'],'amount'=>$data['total_fee'],'payments_type'=>1,'create_time'=>time(),'payments_reason'=>'购买：'.$api_name."  ",'order_id'=>$order_id);
        $add_pay_history = $payhistoryModel->data($pay_history_data)->add();

        $uservaultModel = M('UserVault');
        //先查询是否有该用户记录
        $uservault_count = $uservaultModel->where('uid='.$order_info['works_uid'])->count();//->lock(true)
        if($uservault_count){
           $uservault_result = $uservaultModel->where('uid='.$order_info['works_uid'])->setInc("amount",$data['total_fee']);

        }else{
            $user_vault_data = array('uid'=>$order_info['works_uid'],'user_name'=>'test','amount'=>$data['total_fee']);
            $uservault_result = $uservaultModel->data($user_vault_data)->add();
        }
        
        //购买服务，新增购买数量-modify 20161024 start
        $serviceModel = M('Services');
        $serviceModel->where("service_id=".$order_info['service_id'])->setInc('call_num');
        //购买服务，新增购买数量-modify 20161024 end

        if ($uservault_result && $add_pay_history && $update_order_status){
            // 提交事务
            $orderModel->commit();

            //成功
            $pay_success_destination = C('LOG_PATH').'pay_success/'.date('y_m_d').'.log';
            $pay_success_message = "付款及状态更新成功-订单编号:".$order_id."-金额:".$data['total_fee']."元人民币-"."-用户邮箱:".$user_email."-用户uid:".$user_id."-服务编号:".$service_id."-API编号:".$api_id."-套餐名称:".$package_name;
            \Think\Log::write($pay_success_message,'INFO',$type='',$pay_success_destination);
            return true;
        }else{
            //日志记录，短信通知
            $pay_updatesql_fail_destination = C('LOG_PATH').'paysucces_updatesql_fail/'.date('y_m_d').'.log';
            $pay_updatesql_fail_message = "付款成功,更新订单及账户金额失败-订单编号:".$order_id."-金额:".$data['total_fee']."元人民币-"."-用户邮箱:".$user_email."-用户uid:".$user_id."-服务编号:".$service_id."-API编号:".$api_id."-套餐名称:".$package_name;
            \Think\Log::write($pay_updatesql_fail_message,'INFO',$type='',$pay_updatesql_fail_destination);

           // 事务回滚
           $orderModel->rollback();

           return false;
        }
    }

}